<template>
  <div>
    <el-page-header content="新闻列表" icon="" title="新闻管理" />

    <el-card style="margin-top: 20px; height: calc(100vh - 150px)">
      <div class="search-box">
        <el-input
          placeholder="请输入搜索内容"
          v-model="tableForm.searchValue"
          style="width: 300px; height: 35px"
          @keyup.enter="handleSearch"
        >
          <template #suffix>
            <Search class="search-icon" @click="handleSearch" />
          </template>
        </el-input>
      </div>

      <el-table
        :data="tableData"
        :default-sort="{
          prop: tableForm.sortField,
          order: processOrder(tableForm.sortOrder),
        }"
        @sort-change="changeTableSort"
      >
        <el-table-column
          prop="title"
          label="标题"
          width="200"
          sortable="custom"
        >
          <template #default="scope">
            <span class="to-ellipsis" :title="scope.row.title">
              {{ scope.row.title }}
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="category" label="类别" sortable="custom">
          <template #default="scope">
            {{ categoryFormat(scope.row.category) }}
          </template>
        </el-table-column>

        <el-table-column prop="createdAt" label="创建时间" sortable="custom">
        </el-table-column>

        <el-table-column prop="updatedAt" label="更新时间" sortable="custom">
        </el-table-column>

        <el-table-column
          prop="isPublish"
          label="发布状态"
          sortable="custom"
          width="120"
          align="center"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.isPublish"
              :active-value="1"
              :inactive-value="0"
              :before-change="() => handleSwitchChange(scope.row)"
              :loading="scope.row.isUpdating"
            />
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template v-slot="scope">
            <!-- 预览 -->
            <el-button
              circle
              :icon="View"
              type="success"
              @click="handlePreview(scope.row)"
            ></el-button>
            <!-- 编辑 -->
            <el-button
              circle
              :icon="Edit"
              @click="handleEdit(scope.row)"
            ></el-button>
            <!-- 删除 -->
            <el-popconfirm
              title="你确定要删除吗?"
              confirmButtonText="确定"
              cancelButtonText="取消"
              @confirm="handleDelete(scope.row)"
            >
              <template #reference>
                <el-button circle :icon="Delete" type="danger"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        style="height: 30px; justify-content: center"
        background
        layout="total, prev, pager, next, sizes, jumper"
        :page-size="tableForm.limit"
        :page-sizes="[1, 5, 10, 20]"
        :current-page="tableForm.pageNo"
        :total="total"
        :hide-on-single-page="total <= 0"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </el-card>

    <PreviewDialog v-model="openPreviewDialog" :item-data="previewItem" />
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch } from "vue";
import axios from "axios";
import { Search } from "@element-plus/icons-vue";
import PreviewDialog from "@/views/news-manage/components/PreviewDialog.vue";
import { View, Star, Edit, Delete } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { processOrder } from "@/utils/processData";

const router = useRouter();

// 列表请求相关参数
const tableForm = reactive({
  searchValue: "", // 搜索字段
  pageNo: 1, // 页码
  limit: 10, // 每页数据量
  sortField: "createdAt", // 排序字段
  sortOrder: "desc", // 默认降序desc [desc|asc]
});

// 搜索前的页码
const pageNoBeforeSearch = ref(1);
// 总数据量
const total = ref(0);
// 列表数据
const tableData = ref([]);

// 获取列表数据
const getTableData = async () => {
  await axios
    .get("/adminapi/news/listOfPage", { params: { ...tableForm } })
    .then((res) => {
      if (res?.data?.ActionType !== "OK") return;
      tableData.value = res.data.data.records; // 更新列表数据
      total.value = res.data.data.total; // 更新总记录数
    })
    .catch((error) => {
      console.error(error);
    });
};

// 处理页码变化
const handlePageChange = (page) => {
  tableForm.pageNo = page;
  if (tableForm.searchValue === "") pageNoBeforeSearch.value = page;
  getTableData();
};

// 处理每页数据量变化
const handleSizeChange = (limit) => {
  tableForm.limit = limit;
  getTableData();
};

// 排序
const changeTableSort = (column) => {
  if (column.order) {
    tableForm.sortOrder = processOrder(column.order);
  }
  if (column.prop) {
    tableForm.sortField = column.prop;
  }
  getTableData();
};

// 删除单条数据
const handleDelete = async (data) => {
  await axios
    .delete(`/adminapi/news/list/${data._id}`)
    .then((res) => {
      getTableData(); //tabledata 本地删除后重新刷新新闻列表
    })
    .catch((error) => {
      console.error(error);
    });
};

// 搜索
const handleSearch = () => {
  getTableData();
};
watch(
  () => tableForm.searchValue,
  (newValue, oldValue) => {
    if (newValue === "") {
      tableForm.pageNo = pageNoBeforeSearch.value;
      getTableData();
    }
  }
);

//格式化分类信息
const categoryFormat = (category) => {
  const obj = {
    1: "最新动态",
    2: "典型案例",
    3: "通知公告",
  };
  return obj[category];
};

//开关回调
const handleSwitchChange = async (item) => {
  try {
    if (item.isUpdating) return;
    // 开启加载状态
    item.isUpdating = true;

    // 获取当前开关的新值
    const newValue = item.isPublish === 0 ? 1 : 0;

    // 调用接口更新状态
    await axios.put(`/adminapi/news/publish`, {
      _id: item._id,
      isPublish: newValue,
    });

    return true; // 操作成功，允许状态改变
  } catch (error) {
    return false; // 操作失败，阻止状态改变
  } finally {
    item.isUpdating = false; // 关闭加载状态
  }
};

// 编辑
const handleEdit = (item) => {
  router.push(`/news-manage/NewsEdit${item._id}`);
};

// 预览
const openPreviewDialog = ref(false);
// 当前预览的数据
const previewItem = ref({});
const handlePreview = (item) => {
  previewItem.value = item;
  openPreviewDialog.value = true;
};

onMounted(() => {
  getTableData();
});
</script>

<style lang="scss" scoped>
/*溢出省略号*/
.to-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

:deep() {
  .el-pagination__rightwrapper {
    justify-content: center;
  }
  .el-card__body {
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
  .el-table {
    width: 100%;
    height: calc(100% - 105px);
    flex: 1;
  }
  .el-scrollbar__view {
    height: 100%;
  }
  .el-table__empty-block {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .el-table__inner-wrapper:before {
    background-color: unset;
  }
}
.search-box {
  width: 100%;
  height: 35px;
  display: flex;
  justify-content: right;
  .search-icon {
    width: 16px;
    height: 16px;
    cursor: pointer;
    &:hover {
      color: var(--el-menu-active-color);
    }
  }
}
</style>